package ThreadPoolDemo.bilibiliThread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

	public static void main(String[] args) {
		final Business2 business = new Business2();
		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					business.sub(i);
				}

			}
		}).start();
		for (int i = 0; i < 50; i++) {
			business.main(i);
		}
	}

}

class Business2 {
	Lock lock = new ReentrantLock();
	private boolean bShouldSub = true;

	public void sub(int i) {
		lock.lock();
		try {
			while (!bShouldSub) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int j = 0; j <= 10; j++) {
				System.out.println("sub thread sequece of " + j + ",loop of "
						+ i);
			}
			bShouldSub = false;
			this.notify();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {

			lock.unlock();
		}

	}

	public synchronized void main(int i) {
		while (bShouldSub) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 0; j <= 100; j++) {
			System.out.println("main thread sequece of " + j + ",loop of " + i);
		}
		bShouldSub = true;
		this.notify();
	}
}
